# coding=utf-8
'''
Created on 2017年11月6日

@author: hhl
'''
import json
import requests
import urllib

BD_API_KEY = 'uwhGtvGCfuVqW7s95rE9TWlp'
BD_API_SECRET = '4AO7OTZd6B4pppoKp2kGMyu2zK4XFWV2'

class BaiDuAuthSDK():
    """百度授权调用
    """
    def __init__(self,api_key,api_secret):
        self.authorize = 'http://openapi.baidu.com/oauth/2.0/authorize?'
        self.app_key = api_key
        self.app_secret = api_secret
        self.token_url = 'https://openapi.baidu.com/oauth/2.0/token?'
        self.get_info_url = 'https://openapi.baidu.com/rest/2.0/passport/users/getInfo?'
    
    def dict2url(self, parms):
        parm_items = sorted(parms.items(), key=lambda d: d[0])
        parmlist = ["%s=%s"%item for item in parm_items]
        parm_str =  "&".join(parmlist)
        return parm_str
    
    def create_authorize_url(self, redirect_url):
        #授权链接
        parms = {'response_type':'code','client_id':self.app_key,'redirect_uri':'',
                'display':'mobile'}
        parms['redirect_uri'] = urllib.quote(redirect_url)
        params_str = self.dict2url(parms)
        url = '%s%s'%(self.authorize,params_str)
        return url
    
    def get_token_url(self,code,redirect_url):
        #构建获取token链接
        token_params = {'grant_type':'authorization_code','code':code,
                        'client_id':self.app_key,
                        'client_secret':self.app_secret,'redirect_uri':''}
        print 
        token_params['redirect_uri'] = urllib.quote(redirect_url)
        params_str = self.dict2url(token_params)
        url = '%s%s'%(self.token_url,params_str)
        return url
    
    def get_token(self, code,redirect_url=''):
        get_token_url = self.get_token_url(code, redirect_url)
        print get_token_url
        result = requests.get(get_token_url) 
        print result
        data = result.json()
        print data
        return data['access_token']
    
    def get_user_info(self,access_token):
        user_info_url = '%saccess_token=%s'%(self.get_info_url,access_token)
        print user_info_url
        result = requests.get(user_info_url)
        print result.text
        data = json.loads(result.text)
        return data
    
bdclient = BaiDuAuthSDK(BD_API_KEY, BD_API_SECRET)

if __name__ == '__main__':
    url = 'http://game.meet.henkuai.com/auth/baidu_auth?bkurl=http%3A%2F%2Fgame.meet.henkuai.com%2Fauth%2Flogin_redirect%3Fredirect_to%3Dhttp%253A%252F%252Fgame.meet.henkuai.com%252Fgames%252Fuser_center'
#     print urllib.unquote(url)
#     code = '6f4345be2f82d1d45063b3944da6d4db'
    redirect_url = 'http://game.meet.henkuai.com/test/baidu/authorize'
#     token = bdclient.get_token(code,redirect_url)
#     print token
#     user_info = bdclient.get_user_nifo(token)
#     print user_info
    print bdclient.create_authorize_url(redirect_url)
    